/*!
 * \file TraderYD.h
 * \project WonderTrader
 *
 * \author Wesley
 * \date 2020/03/30
 * 
 * \brief YD交易接口实现
 * 
 * \details YD交易接口适配器，基于易达交易系统API实现
 *          提供期货交易的完整功能，支持期货交易、查询等操作
 *          采用异步回调机制，支持多线程安全操作
 */
#pragma once

#include <string>
#include <queue>
#include <stdint.h>

#include "../Includes/WTSTypes.h"
#include "../Includes/ITraderApi.h"
#include "../Includes/WTSCollection.hpp"

#include "../API/yd1.108.360/ydApi.h"

#include "../Share/IniHelper.hpp"
#include "../Share/StdUtils.hpp"
#include "../Share/DLLHelper.hpp"

USING_NS_WTP;

/*!
 * \class TraderYD
 * \brief YD交易接口实现类
 * 
 * \details YD交易接口适配器，继承自ITraderApi和YDListener
 *          实现WonderTrader统一交易接口，封装YD API的具体实现
 *          
 *          主要功能：
 *          - YD交易连接管理：支持交易服务器连接、断线重连
 *          - 用户认证登录：支持用户名密码登录、账户认证
 *          - 期货订单管理：支持期货买卖订单提交、撤单操作
 *          - 持仓查询：支持期货持仓查询、持仓明细查询
 *          - 资金查询：支持账户资金查询、可用资金计算
 *          - 成交查询：支持历史成交查询、实时成交推送
 *          - 数据转换：WonderTrader数据结构与YD数据结构互转
 *          - 异步处理：支持多线程异步处理，避免阻塞主线程
 *          - 错误处理：完善的错误处理和异常恢复机制
 *          
 *          YD特色功能：
 *          - 支持易达交易系统的特有功能
 *          - 支持期货现货交易
 *          - 支持快速交易模式
 *          - 支持多账户管理
 *          - 支持实时行情推送
 *          - 支持交易确认机制
 *          
 * \note 使用前需要先初始化并连接到YD交易服务器
 * \warning 所有交易操作都是异步的，结果通过回调函数返回
 * \see ITraderApi, YDListener
 */
class TraderYD : public ITraderApi, public YDListener
{
public:
	TraderYD();
	virtual ~TraderYD();

public:
	virtual void notifyReadyForLogin(bool hasLoginFailed) override;


	virtual void notifyLogin(int errorNo, int maxOrderRef, bool isMonitor) override;


	virtual void notifyFinishInit() override;


	virtual void notifyOrder(const YDOrder *pOrder, const YDInstrument *pInstrument, const YDAccount *pAccount) override;


	virtual void notifyTrade(const YDTrade *pTrade, const YDInstrument *pInstrument, const YDAccount *pAccount) override;


	virtual void notifyFailedOrder(const YDInputOrder *pFailedOrder, const YDInstrument *pInstrument, const YDAccount *pAccount) override;


	virtual void notifyFailedCancelOrder(const YDFailedCancelOrder *pFailedCancelOrder, const YDExchange *pExchange, const YDAccount *pAccount) override;


	virtual void notifyAccount(const YDAccount *pAccount) override;

	virtual void notifyCaughtUp() override;

public:
	/*!
	 * \enum WrapperState
	 * \brief 交易接口状态枚举
	 * 
	 * \details 定义YD交易接口的各种连接和登录状态
	 */
	typedef enum
	{
		WS_NOTLOGIN,		///< 未登录状态
		WS_LOGINING,		///< 正在登录状态
		WS_LOGINED,			///< 已登录状态
		WS_LOGINFAILED,		///< 登录失败状态
		WS_CONFIRM_QRYED,	///< 确认查询状态
		WS_CONFIRMED,		///< 已确认状态
		WS_ALLREADY			///< 全部就绪状态，可以进行交易
	} WrapperState;


private:
	int doLogin();

	//////////////////////////////////////////////////////////////////////////
	//ITraderApi接口实现
public:
	virtual bool init(WTSVariant* params) override;

	virtual void release() override;

	virtual void registerSpi(ITraderSpi *listener) override;

	virtual bool makeEntrustID(char* buffer, int length) override;

	virtual void connect() override;

	virtual void disconnect() override;

	virtual bool isConnected() override;

	virtual int login(const char* user, const char* pass, const char* productInfo) override;

	virtual int logout() override;

	virtual int orderInsert(WTSEntrust* eutrust) override;

	virtual int orderAction(WTSEntrustAction* action) override;

	virtual int queryAccount() override;

	virtual int queryPositions() override;

	virtual int queryOrders() override;

	virtual int queryTrades() override;


protected:
	WTSOrderInfo*	makeOrderInfo(const YDOrder* orderField, const YDInstrument* instInfo);
	WTSEntrust*		makeEntrust(const YDInputOrder *entrustField, const YDInstrument* instInfo);
	WTSTradeInfo*	makeTradeRecord(const YDTrade *tradeField, const YDInstrument* instInfo);
	WTSError*		makeError(int errorno, WTSErroCode ec);

	std::string		generateEntrustID(uint32_t orderRef);
	bool			extractEntrustID(const char* entrustid, uint32_t &orderRef);

	uint32_t		genRequestID();

protected:
	std::string		m_strCfgFile;

	std::string		m_strUser;
	std::string		m_strPass;

	bool			m_bCatchup;
	bool			m_bApiInited;

	std::string		m_strUserName;

	ITraderSpi*		m_sink;
	uint64_t		m_uLastQryTime;

	uint32_t					m_lDate;
	std::atomic<uint32_t>		m_orderRef;		///< 订单引用号计数器

	WrapperState				m_wrapperState;

	YDApi*						m_pUserAPI;
	std::atomic<uint32_t>		m_iRequestID;

	typedef WTSHashMap<std::string> DataMap;
	DataMap*					m_mapPosition;
	DataMap*					m_mapTrades;
	DataMap*					m_mapOrders;
	WTSArray*					m_ayFunds;

	IBaseDataMgr*				m_bdMgr;

	typedef std::queue<CommonExecuter>	QueryQue;
	QueryQue				m_queQuery;
	StdUniqueMutex			m_mtxQuery;
	bool					m_bStopped;
	StdThreadPtr			m_thrdWorker;

	std::string		m_strModule;
	DllHandle		m_hInstYD;
	typedef YDApi* (*YDCreator)(const char *);
	YDCreator		m_funcCreator;

	IniHelper		m_iniHelper;
};

